package com.howie.gulimall.ware.service.impl;

import com.howie.common.constant.WareConstant;
import com.howie.gulimall.ware.entity.PurchaseDetailEntity;
import com.howie.gulimall.ware.service.PurchaseDetailService;
import com.howie.gulimall.ware.service.WareSkuService;
import com.howie.gulimall.ware.vo.MergeVo;
import com.howie.gulimall.ware.vo.PurchaseDoneVo;
import com.howie.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.howie.common.utils.PageUtils;
import com.howie.common.utils.Query;

import com.howie.gulimall.ware.dao.PurchaseDao;
import com.howie.gulimall.ware.entity.PurchaseEntity;
import com.howie.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    PurchaseDetailService purchaseDetailService;
    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnReceivePurchase(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status","0").or().eq("status",1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        // 判断可合并过去有没有采购单
        if(purchaseId == null){
            // 新建采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.baseMapper.insert(purchaseEntity);

            purchaseId = purchaseEntity.getId();
        }
        // 判断是否可以合并采购单
        PurchaseEntity purchaseEntity = this.baseMapper.selectById(purchaseId);
        if(!WareConstant.PurchaseStatusEnum.CREATED.getCode().equals(purchaseEntity.getStatus()) ||
                !WareConstant.PurchaseStatusEnum.ASSIGNED.getCode().equals(purchaseEntity.getStatus())){
            throw new RuntimeException("采购单已被领取，不能合并了哦");
        }
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map(i -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            // 合并采购需求至采购单，实际上是修改采购需求上的采购单信息
            purchaseDetailEntity.setId(i);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(purchaseDetailEntities);
    }

    @Override
    public void received(List<Long> ids) {
        // 1、判断当前采购单是新建或者是已分配状态
        List<PurchaseEntity> purchaseEntities = ids.stream().map(id -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(item -> {
            if (item.getStatus().equals(WareConstant.PurchaseStatusEnum.CREATED.getCode()) ||
                    item.getStatus().equals(WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())) {
                return true;
            }
            return false;
        }).map(item -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode()); // 更新状态
            return item;
        }).collect(Collectors.toList());
        // 2、改变采购单状态
        this.updateBatchById(purchaseEntities);
        // 3、改变采购需求的状态
        purchaseEntities.forEach((item) -> {
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listDetailByPurchaseId(item.getId());
            purchaseDetailEntities.forEach((entity) -> {
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
            });
            purchaseDetailService.updateBatchById(purchaseDetailEntities);
        });
    }
    @Transactional
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        // 1、改变采购单状态(要和采购需求单保持一致，保存逻辑应先确定采购需求单的状态)
        Long id = purchaseDoneVo.getId();
        // 2、改变采购需求的状态
        boolean isFinish = true;
        List<PurchaseItemDoneVo> itemDoneVos = purchaseDoneVo.getItems();
        List<PurchaseDetailEntity> purchaseDetailEntities = new ArrayList<>();
        for(PurchaseItemDoneVo purchaseItemDoneVo : itemDoneVos){
            PurchaseDetailEntity entity = new PurchaseDetailEntity();
            entity.setId(purchaseItemDoneVo.getItemId());
            if(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode().equals(purchaseItemDoneVo.getStatus())){
                isFinish = false;
                // 采购失败
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
            }else{
                // 都采购成功
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                // 3、将成功采购的进行入库(采购都成功才入库)
                PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(purchaseItemDoneVo.getItemId());
                wareSkuService.addStock(purchaseDetailEntity.getSkuId(),purchaseDetailEntity.getWareId(),
                        purchaseDetailEntity.getSkuNum());
            }
            purchaseDetailEntities.add(entity);
        }
        // 保存数据
        purchaseDetailService.updateBatchById(purchaseDetailEntities);

        // 改变采购单
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        if(isFinish){
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
        } else {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        }
        this.updateById(purchaseEntity);
    }

}